package common.fengkai.filepost.conf;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "common.fengkai.filepost.dao.pgsql",sqlSessionFactoryRef = "pgsqlSqlsessionBean")
public class PgsqlDatasourceConfig {
    /**
     * 配置数据源
     * @return
     */
    @Bean("pgsqlDatasource")
    @ConfigurationProperties("spring.datasource.pgsql")
    public DataSource mysqlDataSource(){
        return DataSourceBuilder.create().build();
    }

    /**
     * 配置会话工厂
     */
    @Bean("pgsqlSqlsessionBean")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("pgsqlDatasource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("common.fengkai.filepost.bean.pgbean");
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/pgmapper/*.xml"));
        return factoryBean.getObject();
    }

    /**
     * 配置事务
     * @param dataSource
     * @return
     */
    @Bean(name = "pgsqlTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("pgsqlDatasource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "pgqlSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(
            @Qualifier("pgsqlSqlsessionBean") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
